﻿using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Admin.NET.Application.Service;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using AngleSharp.Dom;
using FluentEmail.Core;
using Furion.FriendlyException;
using Furion.InstantMessaging;
using Furion.RemoteRequest;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Minio.DataModel;
using Nest;
using NServiceKit.Common.Extensions;
using OnceMi.AspNetCore.OSS;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Admin.NET.Application;
/// <summary>
/// 案例服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class car_caseService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<car_case> _rep;
    private readonly IOSSService _OSSService;
    private readonly OSSProviderOptions _OSSProviderOptions;

    public car_caseService(SqlSugarRepository<car_case> rep,
            SqlSugarRepository<SysFile> sysFileRep,
        IOptions<OSSProviderOptions> oSSProviderOptions,
        IOptions<UploadOptions> uploadOptions,
        IOSSServiceFactory ossServiceFactory)
    {
        _rep = rep;
        _OSSProviderOptions = oSSProviderOptions.Value;
        if (_OSSProviderOptions.IsEnable)
            _OSSService = ossServiceFactory.Create(Enum.GetName(_OSSProviderOptions.Provider));
    }

    /// <summary>
    /// 分页查询案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]

    public async Task<SqlSugarPagedList<car_caseOutput>> Page(car_caseInput input)
    {
        List<long?> longs = new List<long?>();
     
        //先用赛选条件查出 map表里的 caseid集合
        if (input.carid > 0 || input.colorId > 0 || input.zhiganId > 0 || input.xilieSubId > 0 || input.sexiId > 0 )
        {

            List<long?> toSearchlongs = new List<long?>();
            if (input.carid > 0)
            {
                toSearchlongs.Add(input.carid);
            }
            if (input.colorId > 0)
            {
                toSearchlongs.Add(input.colorId);
            }
            if (input.zhiganId > 0)
            {
                toSearchlongs.Add(input.zhiganId);
            }
            if (input.xilieSubId > 0)
            {
                toSearchlongs.Add(input.xilieSubId);
            }
            if (input.sexiId > 0)
            {
                toSearchlongs.Add(input.sexiId);
            }

            #region 多个查询条件时，直接用Contains搜索map表出来的是多条件的或关系的 caseid的集合

            //  longs = _rep.Context.Queryable<car_tagmap>()
            //    .Where(m=> toSearchlongs.Contains(m.tagid))

            //   .Select(m =>  m.caseid).ToList();
            #endregion

            #region 先用Contains 找出 group的集合，然后内存里在进行搜索更快
            var group = _rep.Context.Queryable<car_tagmap>()
           .Where(m => toSearchlongs.Contains(m.tagid)).ToList().GroupBy(m => m.caseid);

            longs = group
              .WhereIF(input.carid > 0, m => m.Any(t => t.tagid == input.carid))
              .WhereIF(input.colorId > 0, m => m.Any(t => t.tagid == input.colorId))
                 .WhereIF(input.zhiganId > 0, m => m.Any(t => t.tagid == input.zhiganId))
                    .WhereIF(input.xilieSubId > 0, m => m.Any(t => t.tagid == input.xilieSubId))
                       .WhereIF(input.sexiId > 0, m => m.Any(t => t.tagid == input.sexiId))
                       .Select(m => m.Key).ToList();
            #endregion

        }
        var query = _rep.AsQueryable().Where(m => m.IsDelete == false)
                 //.LeftJoin<car_tagmap>((m, tm) => m.Id == tm.caseid)
                 // .LeftJoin<car_tag>((m, tm, tg) => tm.tagid ==tg.Id)
                 .Includes(m => m.tags, t => t.tag)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.title), u => u.title.Contains(input.title.Trim()))
                         .WhereIF(longs.Count>0,m=> longs.Contains(m.Id))
                     .Select(u => new car_caseOutput
                     {
                         Id = u.Id,
                         imageurls = u.imageurls,
                         coverurl = u.coverurl,
                         clickCount = u.clickCount,
                         tags = u.tags.Where(tg => tg.tag != null).ToList(),
                         title = u.title,

                         tag_sexi = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.sexi).Select(m => m.tag).ToList(),
                         tag_zhigan = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.zhigan).Select(m => m.tag).ToList(),
                         tag_color = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.color).Select(m => m.tag).ToList(),
                         tag_car = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.car).Select(m => m.tag).ToList(),
                         tag_xilie = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.xilie).Select(m => m.tag).ToList(),


                         zhiganList = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.zhigan).Select(m => m.tagid).ToList(),
                         colorList = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.color).Select(m => m.tagid).ToList(),
                         sexiList = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.sexi).Select(m => m.tagid).ToList(),
                         carList = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.car && tg.tag.pid != 0)
                         .Select(m => m.tag).ToList().Select(n => new long[2] { n.pid, n.Id }).ToList(),
                         xilieList = u.tags.Where(tg => tg.tag != null && tg.tag.type == (int?)car_tagType.xilie && tg.tag.pid != 0)
                         .Select(m => m.tag).ToList().Select(n => new long[2] { n.pid, n.Id }).ToList(),
                     }); ;
        //.Mapper(c => c.coverurlAttachment, c => c.coverurl)

        query = query.OrderBuilder(input);


        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task Add(Addcar_caseInput input)
    {

        car_case entity = input.Adapt<car_case>();
        entity= _rep.Context.Insertable(entity).ExecuteReturnEntity();

        foreach (long tagid in input.zhiganList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }

        foreach (long tagid in input.sexiList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }

        foreach (long tagid in input.colorList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }


        foreach (long tagid in input.carList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }


        foreach (long[] tagids in input.xilieList)
        {
            foreach (long tagid in tagids)
            {
                _rep.Context.Insertable(new car_tagmap()
                {
                    caseid = entity.Id,
                    tagid = tagid
                }).AddQueue();
            }
        }
        _rep.Context.SaveQueues();
    }



    /// <summary>
    /// 增加案例 来自客户端
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpPost]
    [ApiDescriptionSettings(Name = "AddFromForm")]
    public long AddFromForm(dynamic postdata)
    {
        #region 创建
        string dinametemp = postdata["dirName"];
        string dirName = MGee.Http.HttpHelper.URLDecode(dinametemp,Encoding.UTF8);
        string files = null;
        try
        {
            files= postdata["files"];
        }
        catch { }
      
        List<car_tag> toaddTag = new List<car_tag>();

        MatchCollection mac = Regex.Matches(dirName, "【(.*?)】");
        string title = null;
        string car = null;
        string xilie = null;

        string zhigan = null;
        string yanse = null;
        string sexi = null;


        #region 处理typ3（系列）模板，没有模板的返回错误，有模板的将模板的subtag加入到toaddTag就可以  同时把标签处理了

        if (mac.Count < 5) 
        {
            title = mac[0].Groups[1].Value.Trim();
            car = mac[1].Groups[1].Value.Trim();
            xilie = mac[2].Groups[1].Value.Trim();

            #region 标签 处理 没有的先添加 这里只处理2个 car 和 xilie
            car_tagType type = car_tagType.xilie;
            var arrxilie = xilie.Split('｜');
           
            string[] arr;
            foreach (var item in arrxilie)
            {
                arr = item.Split('-');
                toaddTag.AddRange(gettagP(arr, type));
            }
         

            type = car_tagType.car;
            arr = car != "" ? car.Split(' ') : null;
            toaddTag.AddRange(gettagP(arr, type));
            #endregion
            //这个有个前端传入xilie如果是多选，就取第一个的系列名字 所以index是1（0是系列的pid 1才是具体系列）
            var sublist= _rep.Context.Queryable<car_tagSub>()
                .Includes(m => m.taginfo).Where(s => s.pid == toaddTag[1].Id).ToList();

            if (sublist.Count(m => m.taginfo == null)>0)
            {
                throw new System.Exception($"模板信息有已删除元素");
            }
            List<car_tag> stbtag =  sublist.Select(m => m.taginfo).ToList();
            if (stbtag.Count == 0)

            {
                throw new System.Exception($"没有找到系列 {toaddTag[1].title} 的模板信息");
            }
            toaddTag.AddRange(stbtag);
        }
        else
        {
            title = mac[0].Groups[1].Value.Trim();
            car = mac[3].Groups[1].Value.Trim();
            xilie = mac[4].Groups[1].Value.Trim();

            zhigan = mac[1].Groups[1].Value.Trim();
            yanse = mac[2].Groups[1].Value.Trim();
            sexi = mac[5].Groups[1].Value.Trim();

            //后面3个属性加到这里先，然后加到整个里面
            List<car_tag> toUpTemp = new List<car_tag>();
            #region 标签 处理 没有的先添加
            car_tagType type = car_tagType.xilie;
            var arrxilie = xilie.Split('｜');
            string[] arr;
            foreach (var item in arrxilie)
            {
                arr = item.Split('-');
                toaddTag.AddRange(gettagP(arr, type));
            }

            type = car_tagType.car;
            arr = car != "" ? car.Split(' ') : null;
            toaddTag.AddRange(gettagP(arr, type));


            type = car_tagType.zhigan;
            arr = zhigan != null ? zhigan.Split('｜') : null;
            toUpTemp.AddRange(gettag(arr, type));

            type = car_tagType.color;
            arr = yanse != null ? yanse.Split('｜') : null;
            toUpTemp.AddRange(gettag(arr, type));


            type = car_tagType.sexi;
            arr = sexi != null ? sexi.Split('｜') : null;
            toUpTemp.AddRange(gettag(arr, type));

            toaddTag.AddRange(toUpTemp);
            #endregion


            //需要把后三个属性加入模板
            //先清空，
            _rep.Context.Deleteable<car_tagSub>().Where(m => m.pid == toaddTag[1].Id).AddQueue();
          

            //在设置新的
            foreach (var item in toUpTemp)
            {
                _rep.Context.Insertable(new car_tagSub()
                {
                    pid = toaddTag[1].Id,
                    tagid =  item.Id,
                    type=item.type,
                    
                }).AddQueue();
            }
            _rep.Context.SaveQueues();

        }
        #endregion



        if (string.IsNullOrEmpty(title))
        {
            return 0;
        }
        car_case entity = new car_case()
        {
            title = title,
            IsDelete = false,

        };
        entity = _rep.Context.Insertable(entity).ExecuteReturnEntity();

        #endregion

     

        #region 加入map
        foreach (var item in toaddTag)
        {
            car_tagmap car_Tagmap = new car_tagmap()
            {
                caseid = entity.Id,
                tagid = item.Id
            };
            _rep.Context.Insertable(car_Tagmap).AddQueue();
        }
        _rep.Context.SaveQueues();
        #endregion

        #region 写入内容 更新封面
        string[] imgArr = files!=null? files.Split("|"):null;
        foreach (var img in imgArr)
        {

            car_case_details csd = new car_case_details()
            {
                caseId = entity.Id,
                des = string.Join("-", toaddTag.Where(m => m.type == (int?)car_tagType.xilie && m.pid != 0).Select(m=>m.title).ToList()),
                IsDelete = false,
                type = 1,
                url = "http://hxhcolor.kemangouwu.top/autoupload/" + entity.Id+"_"+img,


            };
            _rep.Context.Insertable(csd).AddQueue();
        }
      

        //更新实体封面信息
        if (imgArr.Length >= 2)
        {
            entity.coverurl = "http://hxhcolor.kemangouwu.top/autoupload/" + entity.Id + "_" + imgArr[1];
        }
        else if (imgArr.Length == 1)
        {
            entity.coverurl = "http://hxhcolor.kemangouwu.top/autoupload/" + entity.Id + "_" + imgArr[0];

        }
        _rep.Context.Updateable(entity).AddQueue();
        _rep.Context.SaveQueues();

        #endregion

     

        return entity.Id;
    }


    //[AllowAnonymous]
    [HttpGet]
    [ApiDescriptionSettings(Name = "ClearMap")]
    public async Task<string> ClearMap()
    {
       
    //var dellist=    _rep.Context.Queryable<car_case>().Where(m => m.IsDelete==true).ToList();


    //    foreach (var item in dellist)
    //    {
    //    var dellist2=    _rep.Context.Queryable<car_tagmap>().Where(m => m.caseid == item.Id).ToList();
    //        if (dellist2.Count > 0)
    //        {

    //            _rep.Context.Deleteable<car_tagmap>().Where(m => m.caseid == item.Id).AddQueue();
               
    //        }
          
    //    }
    //    int delnum = _rep.Context.SaveQueues();
    //    //  _rep.Context.Deleteable<car_tagmap>().ExecuteCommand();

    //    return delnum.ToString();

        return "";
    }

    private List< car_tag> gettag(string[] titles,car_tagType type)
    {
        List < car_tag > toadd = new List<car_tag>();
        if (titles == null)
        {
            return toadd;
        }
        foreach (var it in titles)
        {
            string itemtemp= it.Trim();
            var tag = _rep.Context.Queryable<car_tag>().Where(m => m.IsDelete==false &&  m.title == itemtemp && m.type == (int?)type).First();
            if (tag == null)
            {
                tag = new car_tag()
                {
                    type = (int?)type,
                    title = itemtemp,
                    IsDelete = false,
                    pid = 0
                };
                tag = _rep.Context.Insertable(tag).ExecuteReturnEntity();


            }
            toadd.Add( tag);
        }
        return toadd;
    }

    /// <summary>
    /// 传入titles都是2个，第一个的pid是0
    /// </summary>
    /// <param name="titles"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    private List<car_tag> gettagP(string[] titles, car_tagType type)
    {
        if (titles == null)
        {
            return  new List<car_tag>();

        }
        List<car_tag> toadd = new List<car_tag>();

        string firtitem = titles[0].Trim();
        var ptag = _rep.Context.Queryable<car_tag>().Where(m => m.IsDelete == false &&  m.title == firtitem && m.type == (int?)type).First();
        if (ptag == null)
        {
            ptag = new car_tag()
            {
                type = (int?)type,
                title = firtitem,
                IsDelete = false,
                pid = 0
            };
            ptag = _rep.Context.Insertable(ptag).ExecuteReturnEntity();


        }
        toadd.Add(ptag);


        string item2 = titles[1].Trim();
        var stag = _rep.Context.Queryable<car_tag>().Where(m => m.IsDelete == false && m.title == item2 && m.type == (int?)type && m.pid== ptag.Id).First();
        if (stag == null)
        {
            stag = new car_tag()
            {
                type = (int?)type,
                title = item2,
                IsDelete = false,
                pid= ptag.Id
            };
            stag = _rep.Context.Insertable(stag).ExecuteReturnEntity();


        }
        toadd.Add(stag);


        return toadd;
    }


    /// <summary>
    /// 删除案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(Deletecar_caseInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        // await _rep.FakeDeleteAsync(entity);   //假删除 修改一下，增加删除map表
        entity.IsDelete = true;
        _rep.Context.Updateable(entity).UpdateColumns(m => new { m.IsDelete }).AddQueue();
    

        _rep.Context.Deleteable<car_tagmap>().Where(m => m.caseid == entity.Id).AddQueue();
     int succount=    _rep.Context.SaveQueues();

        #region 删除文件
        if (succount > 0)
        {
            var details = _rep.Context.Queryable<car_case_details>().Where(m => m.caseId == entity.Id).ToList();

           string   urltemp = entity.coverurl.Replace("http://", "");
            urltemp = urltemp.Replace("https://", ""); //xhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
            urltemp = urltemp.Substring(urltemp.IndexOf("/"));

            string BucketName = _OSSProviderOptions.IsEnable ? _OSSProviderOptions.Bucket : "Local";
            await _OSSService.RemoveObjectAsync(BucketName, urltemp);

            foreach (var item in details)
            {
                // http://hxhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
                 urltemp = item.url.Replace("http://", "");
                 urltemp = urltemp.Replace("https://", ""); //xhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
                urltemp = urltemp.Substring(urltemp.IndexOf("/"));
                 
                await _OSSService.RemoveObjectAsync(BucketName, urltemp);
            }
        }
        #endregion
    }


    //[AllowAnonymous]
    [HttpGet]
    [ApiDescriptionSettings(Name = "deletaalll")]
    public void deletaalll()
    {
        //string BucketName = _OSSProviderOptions.IsEnable ? _OSSProviderOptions.Bucket : "Local";
        //var all = _rep.GetList();
        //foreach (var entity in all)
        //{


        //    //    entity.IsDelete = true;
        //    //   _rep.Context.Updateable(entity).UpdateColumns(m => new { m.IsDelete }).AddQueue();



        //    #region 删除文件

        //    var details = _rep.Context.Queryable<car_case_details>().Where(m => m.caseId == entity.Id).ToList();
        //    string urltemp = "";
        //    if (entity.coverurl != null)
        //    {


        //         urltemp = entity.coverurl.Replace("http://", "");
        //        urltemp = urltemp.Replace("https://", ""); //xhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
        //        urltemp = urltemp.Substring(urltemp.IndexOf("/"));


        //        try
        //        {
        //            _OSSService.RemoveObjectAsync(BucketName, urltemp);
        //        }
        //        catch (Exception e)
        //        {
        //            if (!e.Message.Contains("no such file or directory"))
        //            {
        //                Console.WriteLine(e.Message);
        //            }
        //        }
        //    }

        //    foreach (var item in details)
        //    {
        //        //已经删除的封面跳过
        //        if (item.url == entity.coverurl)
        //        {
        //            continue;
        //        }
        //        // http://hxhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
        //        urltemp = item.url.Replace("http://", "");
        //        urltemp = urltemp.Replace("https://", ""); //xhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
        //        if (urltemp.IndexOf("/") == -1)
        //        {
        //            continue;
        //        }
        //        urltemp = urltemp.Substring(urltemp.IndexOf("/"));
        //        try
        //        {
        //            _OSSService.RemoveObjectAsync(BucketName, urltemp);
        //        }
        //        catch (Exception e)
        //        {
        //            if (!e.Message.Contains("no such file or directory"))
        //            {
        //                Console.WriteLine(e.Message);
        //            }
        //        }
        //    }
        //    //删除内容
        //    _rep.Context.Deleteable(entity).AddQueue();
        //    _rep.Context.Deleteable<car_case_details>().Where(m => m.caseId == entity.Id).AddQueue();
        //    _rep.Context.Deleteable<car_tagmap>().Where(m => m.caseid == entity.Id).AddQueue();
        //    int succount = _rep.Context.SaveQueues();

        //    #endregion
        //}
    
        //   var detailsall = _rep.Context.Queryable<car_case_details>().ToList();

        //foreach (var item in detailsall)
        //{
        //    //已经删除的封面跳过
            
        //    // http://hxhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
        //  var  urltemp = item.url.Replace("http://", "");
        //    urltemp = urltemp.Replace("https://", ""); //xhcolor.kemangouwu.top/autoupload/22732195244357_003.webp
        //    urltemp = urltemp.Substring(urltemp.IndexOf("/"));
        //    try
        //    {
        //        _OSSService.RemoveObjectAsync(BucketName, urltemp);
        //    }
        //    catch (Exception e)
        //    {
        //        if (!e.Message.Contains("no such file or directory"))
        //        {
        //            Console.WriteLine(e.Message);
        //        }
        //    }
        //}

    }


    [AllowAnonymous]
    [HttpGet]
    [ApiDescriptionSettings(Name = "SetMap")]
    public int  SetMap()
    {
        List<car_case> entitys =   _rep.AsQueryable().Where(m => m.IsDelete == false).ToList();

        foreach (var item in entitys)
        {
            car_tagmap map = new car_tagmap()
            {
                 caseid=item.Id,
                  tagid=item.carid,

            };

            car_tagmap map2 = new car_tagmap()
            {
                caseid = item.Id,
                tagid = item.zhiganId,

            };

            car_tagmap map3 = new car_tagmap()
            {
                caseid = item.Id,
                tagid = item.xilieSubId,
                 
            };

            car_tagmap map4 = new car_tagmap()
            {
                caseid = item.Id,
                tagid = item.colorId,

            };
            car_tagmap map5 = new car_tagmap()
            {
                caseid = item.Id,
                tagid = item.sexiId,

            };

            _rep.Context.Insertable(map).AddQueue();
            _rep.Context.Insertable(map2).AddQueue();
            _rep.Context.Insertable(map3).AddQueue();
            _rep.Context.Insertable(map4).AddQueue();
            _rep.Context.Insertable(map5).AddQueue();
        }
        return _rep.Context.SaveQueues();
       
    }

  

    /// <summary>
    /// 更新案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(Updatecar_caseInput input)
    {
        car_case entity = input.Adapt<car_case>();
      var todelmap=  _rep.Context.Queryable<car_tagmap>().Where(m => m.caseid == input.Id).ToList();
        _rep.Context.Deleteable(todelmap).ExecuteCommand();

        foreach (long tagid in input.zhiganList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }

        foreach (long tagid in input.sexiList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }

        foreach (long tagid in input.colorList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }


        foreach (long tagid in input.carList)
        {
            _rep.Context.Insertable(new car_tagmap()
            {
                caseid = entity.Id,
                tagid = tagid
            }).AddQueue();
        }


        foreach (long[] tagids in input.xilieList)
        {
            foreach (long tagid in tagids)
            {
                _rep.Context.Insertable(new car_tagmap()
                {
                    caseid = entity.Id,
                    tagid = tagid
                }).AddQueue();
            }
        }
        _rep.Context.SaveQueues();

        
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取案例
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<car_case> Get([FromQuery] QueryByIdcar_caseInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取案例列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<car_caseOutput>> List([FromQuery] car_caseInput input)
    {
        return await _rep.AsQueryable().Select<car_caseOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取车型id列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "car_carDropdown"), HttpGet]
    public List<TreeModel> car_carDropdown()
    {
        var lists = _rep.Context.Queryable<car_tag>()
              .Where(m => m.IsDelete == false && m.type == (int?)car_tagType.car ).ToList();

        var listsPid = lists.Where(m => m.pid == 0).ToList();

        List<TreeModel> reList = new List<TreeModel>();
        foreach (var item in listsPid)
        {
            reList.Add(new TreeModel()
            {
                label = item.title,
                value = item.Id,
                children = lists.Where(m => m.pid == item.Id).Select(u=>new TreeModelItem
                { 
                 label= u.title,
                  value =u.Id,
                
                }).ToList(),
            });
        }
        return reList;
        //return await _rep.Context.Queryable<car_car>().GroupBy(m=>m.pid)
        //        .Select(u => new
        //        {
        //            Label = u.carname,
        //            Value = u.Id
        //        }
        //        ).ToListAsync();
    }

    /// <summary>
    /// 颜色分类
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "car_colorDropdown"), HttpGet]
    public List<TreeModel> car_colorDropdown()
    {
        var lists = _rep.Context.Queryable<car_tag>()
              .Where(m => m.IsDelete == false && m.type == (int?)car_tagType.xilie).ToList();

        var listsPid = lists.Where(m => m.pid == 0).ToList();

        List<TreeModel> reList = new List<TreeModel>();
        foreach (var item in listsPid)
        {
            reList.Add(new TreeModel()
            {
                label = item.title,
                value = item.Id,
                children = lists.Where(m => m.pid == item.Id).Select(u => new TreeModelItem
                {
                    label = u.title,
                    value = u.Id,

                }).ToList(),
            });
        }
        return reList;
        //return await _rep.Context.Queryable<car_car>().GroupBy(m=>m.pid)
        //        .Select(u => new
        //        {
        //            Label = u.carname,
        //            Value = u.Id
        //        }
        //        ).ToListAsync();
    }


    /// <summary>
    /// 获取颜色id列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "car_color2Dropdown"), HttpGet]
    public async Task<dynamic> car_color2Dropdown()
    {
        var lists = _rep.Context.Queryable<car_tag>()
            .Where(m => m.IsDelete == false && m.type == (int?)car_tagType.color)
            .Select(m => new TreeModel
            {
                label = m.title,
                value = m.Id,

            }).ToList();

     

      
        return lists;
    }
    /// <summary>
    /// 获取质感id列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "car_zhiganDropdown"), HttpGet]
    public async Task<dynamic> car_zhiganDropdown()
    {
        var lists = _rep.Context.Queryable<car_tag>()
             .Where(m => m.IsDelete == false && m.type == (int?)car_tagType.zhigan)
             .Select(m => new TreeModel
             {
                 label = m.title,
                 value = m.Id,

             }).ToList();




        return lists;
    }

    /// <summary>
    /// 获取色系id列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "car_SeXiDropdown"), HttpGet]
    public async Task<dynamic> car_SeXiDropdown()
    {
        var lists = _rep.Context.Queryable<car_tag>()
             .Where(m => m.IsDelete == false && m.type == (int?)car_tagType.sexi)
             .Select(m => new TreeModel
             {
                 label = m.title,
                 value = m.Id,

             }).ToList();

        return lists;
    }

    /// <summary>
    /// 上传封面图
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Uploadcoverurl"), HttpPost]
    public async Task<FileOutput> Uploadcoverurl([Required] IFormFile file)
    {
            var service = App.GetService<SysFileService>();
            return await service.UploadFile(file, "upload/coverurl"); 
    } 



}

